import logger from '../core/logger';
import { clientBase } from './core/clientBase';
import settingHelper from '../core/settingHelper';
import returnModel from '../model/common/returnModel';
import danmakuFilter from '../model/danmaku/danmakuFilter';
import danmakuFilterTab from '../model/danmaku/danmakuFilterTab';
import { emptyData } from '../model/common/emptyData';

class danmakuFilterClient extends clientBase {
  constructor() {
    super();
  }

  add(type: number, data: string, csrf: string): Promise<returnModel<emptyData>> {
    return new Promise((resolve) => {
      try {
        let info = `type=${type}&filter=${data}&jsonp=jsonp&csrf=${csrf}`;
        this.client.postResult('http://api.bilibili.com/x/dm/filter/user/add', info).then((res) => {
          if (res.code == '0') {
            let oid = res.data.id.toString();
            settingHelper.addDanmakuFilter(type, oid, data);
            resolve(this.buildSuccessResult<emptyData>());
          } else {
            resolve(this.buildFailedResult<emptyData>(res.toString()));
          }
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<emptyData>(e));
      }
    });
  }

  get(type: number): Promise<returnModel<Array<danmakuFilterTab>>> {
    return new Promise((resolve) => {
      try {
        this.client.getResult('http://api.bilibili.com/x/dm/filter/user?jsonp=jsonp').then((res) => {
          let data: danmakuFilter = res;
          if (data.code == 0) {
            for (let item of data.rule) {
              let oid = item.id.toString();
              settingHelper.addDanmakuFilter(type, oid, item.filter);
            }
          }
          resolve(this.buildSuccessResult(this.getFromDB(type)));
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<Array<danmakuFilterTab>>(e));
      }
    });
  }

  delete(ids: Array<string>, type: number, csrf: string): void {
    for (let id of ids) {
      try {
        let info = `ids=${id}&jsonp=jsonp&csrf=${csrf}`;
        this.client.postResult("https://api.bilibili.com/x/dm/filter/user/del", info).then((res) => {
          let data: danmakuFilter = res;
          if (data.code == 0)
            settingHelper.removeDanmakuFilter(id, type);
        });
      } catch (e) {
        logger.error(e);
      }
    }
  }

  getFromDB(type?: number): Array<danmakuFilterTab> {
    return settingHelper.getDanmakuFilter(type);
  }
}
export default new danmakuFilterClient();